package com.buss.article.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.buss.areainfo.entity.AreaInfoEntity;
import com.buss.article.entity.BnsArticleEntity;
import com.buss.article.service.BnsArticleServiceI;
import com.buss.articlegroup.entity.ArticleGroupInfoEntity;
import com.buss.theme.entity.BnsThemeEntity;

/**
 * @Title: Controller
 * @Description: 文章表
 * @author onlineGenerator
 * @date 2016-08-30 10:08:30
 * @version V1.0
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/bnsArticleController")
public class BnsArticleController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(BnsArticleController.class);

	@Autowired
	private BnsArticleServiceI bnsArticleService;
	@Autowired
	private SystemService systemService;
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 文章表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/buss/article/bnsArticleList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(BnsArticleEntity bnsArticle, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(BnsArticleEntity.class, dataGrid);
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsArticle, request.getParameterMap());
//		cq.eq("themeId", "402888ef56c496a00156c49980320001");
		try {
			// 自定义追加查询条件
			String query_createDate_begin = request.getParameter("createDate_begin");
			String query_createDate_end = request.getParameter("createDate_end");
			if (StringUtil.isNotEmpty(query_createDate_begin)) {
				cq.ge("createDate", new SimpleDateFormat("yyyy-MM-dd").parse(query_createDate_begin));
			}
			if (StringUtil.isNotEmpty(query_createDate_end)) {
				cq.le("createDate", new SimpleDateFormat("yyyy-MM-dd").parse(query_createDate_end));
			}
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.bnsArticleService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除文章表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(BnsArticleEntity bnsArticle, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		bnsArticle = systemService.getEntity(BnsArticleEntity.class, bnsArticle.getId());
		message = "文章表删除成功";
		try {
			bnsArticleService.delete(bnsArticle);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "文章表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除文章表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "文章表删除成功";
		try {
			for (String id : ids.split(",")) {
				BnsArticleEntity bnsArticle = systemService.getEntity(BnsArticleEntity.class, id);
				bnsArticleService.delete(bnsArticle);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "文章表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 选择版块跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "chooseGroup")
	public ModelAndView chooseGroup(HttpServletRequest request) {
		// --author：zhoujf-----start----date:20150531--------for:
		// 编辑用户，选择角色,弹出的角色列表页面，默认没选中
		ModelAndView mv = new ModelAndView("com/buss/articlegroup/chooseGroup");
		String ids = oConvertUtils.getString(request.getParameter("ids"));
		mv.addObject("ids", ids);
		return mv;
		// --author：zhoujf-----end------date:20150531--------for:
		// 编辑用户，选择角色,弹出的角色列表页面，默认没选中
	}

	/**
	 * 版块显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridChooseGroup")
	public void datagridChooseGroup(ArticleGroupInfoEntity bnsGroupEntity, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ArticleGroupInfoEntity.class, dataGrid);
		// 查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsGroupEntity);
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 添加文章表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(BnsArticleEntity bnsArticle, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "文章表添加成功";
		try {
			String areaId = request.getParameter("area"); // 区域ID
			String groupId = request.getParameter("group"); // 版块ID
			String themeId = request.getParameter("theme"); // 主题id
			
			if(areaId.contains("请选择")){
				j.setMsg("请选择区域");
				j.setSuccess(false);
				return j;
			}
			
			if(groupId.contains("请选择")){
				j.setMsg("请选择版块");
				j.setSuccess(false);
				return j;
			}
			
			if (StringUtil.isEmpty(themeId)||themeId.equals("请选择主题")) {
				themeId = "";
			}
//			String createName = request.getParameter("createName");
//			String title = request.getParameter("title");
//			String content = request.getParameter("content");			
//			String publisherStates = request.getParameter("publisherStates");
//			String isUp = request.getParameter("isUp");
			// 新建一个文章实体
			BnsArticleEntity myArticle = new BnsArticleEntity();

			// 保存区域id和版块id到实体中
			myArticle.setAreaId(areaId);
			myArticle.setGroupId(groupId);
			// 保存其他参数到实体中
			// myArticle.setId(id);
			myArticle.setCreateName(bnsArticle.getCreateName());
			myArticle.setCreateDate(new Date());
			myArticle.setTitle(bnsArticle.getTitle());
			myArticle.setContent(bnsArticle.getContent());   
			myArticle.setThemeId(bnsArticle.getThemeId());
			myArticle.setArticleLabel(bnsArticle.getArticleLabel());
			myArticle.setPublisherStates(bnsArticle.getPublisherStates());
			myArticle.setIsUp(bnsArticle.getIsUp());
			myArticle.setCommentsNum(0);
			myArticle.setBrowseNum(0); 
			// 保存实体
			bnsArticleService.save(myArticle);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "文章表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新文章表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(BnsArticleEntity bnsArticle, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String areaId = request.getParameter("area"); // 区域ID
		String groupId = request.getParameter("group"); // 版块ID
		String themeId = request.getParameter("theme"); // 主题id
		
		message = "文章表更新成功";
		BnsArticleEntity t = bnsArticleService.get(BnsArticleEntity.class, bnsArticle.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(bnsArticle, t);
			if(!areaId.contains("请选择")){
				t.setAreaId(areaId);
			}
			
			if(!groupId.contains("请选择")){
				t.setGroupId(groupId);
			}
			
			if (!themeId.equals("请选择主题")) {
				t.setThemeId(themeId);
			}
			
			bnsArticleService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "文章表更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 文章表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(BnsArticleEntity bnsArticle, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(bnsArticle.getId())) {
			bnsArticle = bnsArticleService.getEntity(BnsArticleEntity.class, bnsArticle.getId());

		}
		bnsArticle.setPublisherStates("pbsSta_wfb");
		bnsArticle.setIsUp("N");

		List<AreaInfoEntity> arealist = systemService.loadAll(AreaInfoEntity.class);

		req.setAttribute("arealist", arealist);
		req.setAttribute("bnsArticlePage", bnsArticle);
		return new ModelAndView("com/buss/article/bnsArticle-add");
	}
	
	/**
	 * 获取区域选项
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(params = "getAreaGroup")
	public void getAreaGroup(HttpServletRequest request, HttpServletResponse response) throws IOException{
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/xml");
		String flag=request.getParameter("flag");
//		System.out.println(flag);
		String super_id=request.getParameter("id");
		if(flag!=null&&"getArea".equals(flag))
		{
			List<ArticleGroupInfoEntity> groupInofList= systemService.findByProperty(ArticleGroupInfoEntity.class,"areaId", super_id);
			
			StringBuffer sb=new StringBuffer();
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			sb.append("<groups>");
			for(ArticleGroupInfoEntity group:groupInofList)
			{
				sb.append("<element>");
				sb.append("<id>");
				sb.append(group.getId());
				sb.append("</id>");
				sb.append("<name>");
				sb.append(group.getArticleGroupName());
				sb.append("</name>");
				sb.append("<sid>");
				sb.append(group.getAreaId());
				sb.append("</sid>");
				sb.append("</element>");
			}
			sb.append("</groups>");
//			System.out.println(sb);
			PrintWriter out=response.getWriter();
//			System.out.println(sb.toString());
			out.print(sb.toString());
			out.flush();
			out.close();
		}
		if(flag!=null&&"getGroup".equals(flag))
		{
			List<BnsThemeEntity> themeList= systemService.findByProperty(BnsThemeEntity.class,"groupId", super_id);
			
			StringBuffer sb=new StringBuffer();
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			sb.append("<themes>");
			for(BnsThemeEntity theme:themeList)
			{
				sb.append("<element>");
				sb.append("<id>");
				sb.append(theme.getId());
				sb.append("</id>");
				sb.append("<name>");
				sb.append(theme.getThemeName());
				sb.append("</name>");
				sb.append("<sid>");
				sb.append(theme.getGroupId());
				sb.append("</sid>");
				sb.append("</element>");
			}
			sb.append("</themes>");
//			System.out.println(sb);
			PrintWriter out=response.getWriter();
			out.print(sb.toString());
			out.flush();
			out.close();
		}
	}

	/**
	 * 文章表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(BnsArticleEntity bnsArticle, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(bnsArticle.getId())) {
			bnsArticle = bnsArticleService.getEntity(BnsArticleEntity.class, bnsArticle.getId());
			req.setAttribute("bnsArticlePage", bnsArticle);
		}
		List<AreaInfoEntity> arealist = systemService.loadAll(AreaInfoEntity.class);
		List<ArticleGroupInfoEntity> grouplist = systemService.loadAll(ArticleGroupInfoEntity.class);
		List<BnsThemeEntity> themelist = systemService.loadAll(BnsThemeEntity.class);
		req.setAttribute("arealist", arealist);
		req.setAttribute("grouplist", grouplist);
		req.setAttribute("themelist", themelist);
		return new ModelAndView("com/buss/article/bnsArticle-update");
	}

	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "bnsArticleController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}

	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(BnsArticleEntity bnsArticle, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(BnsArticleEntity.class, dataGrid);
		cq.addOrder("createDate", SortDirection.desc);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, bnsArticle, request.getParameterMap());
		List<BnsArticleEntity> bnsArticles = this.bnsArticleService.getListByCriteriaQuery(cq, false);
		modelMap.put(NormalExcelConstants.FILE_NAME, "文章表");
		modelMap.put(NormalExcelConstants.CLASS, BnsArticleEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("文章表列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, bnsArticles);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(BnsArticleEntity bnsArticle, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
		modelMap.put(NormalExcelConstants.FILE_NAME, "文章表");
		modelMap.put(NormalExcelConstants.CLASS, BnsArticleEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("文章表列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<BnsArticleEntity> listBnsArticleEntitys = ExcelImportUtil.importExcel(file.getInputStream(), BnsArticleEntity.class, params);
				for (BnsArticleEntity bnsArticle : listBnsArticleEntitys) {
					bnsArticleService.save(bnsArticle);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
}
